package com.lagou.flink.work.p5;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.util.Collector;
import scala.Tuple2;

/**
 * 功能描述：并行度设置
 * client级别并行度设置
 *./bin/flink run -p 10 WordCount-java.jar
 * system级别并行度设置
 * 在系统级可以通过设置flink-conf.yaml文件中的parallelism.default属性来指定所有执行环境的默认并行度
 * @author : zhangyong
 * @since : 2021/5/18
 */
public class Work5 {
    public static void main(String[] args) throws Exception {
        String inputStr = args[0];
        String outputStr = args[1];
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //ENV级别并行度设置
        env.setParallelism(4);

        DataSet<String> textInfo = env.readTextFile(inputStr);
        DataSet<Tuple2<String, Integer>> sumDs = textInfo
                .flatMap(new LineSplitter()).groupBy(0).
                        sum(1).setParallelism(4);//算子级别并行度设置
        sumDs.writeAsCsv(outputStr,"\n","").setParallelism(1);
        env.execute();
    }

    static class LineSplitter implements FlatMapFunction<String,
                scala.Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<scala.Tuple2<String, Integer>> collector) throws Exception {
            for (String word : s.split(" ")) {
                collector.collect(new scala.Tuple2<>(word, 1));
            }
        }
    }
}
